package com.example.controller;

import com.aliyuncs.exceptions.ClientException;
import com.example.models.ResultList;
import com.example.models.Url;
import com.example.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

// Slf4j注解添加后可以使用log.info添加日志
@Slf4j
// @CrossOrigin(origins = "*")配置cross防止请求跨域
@CrossOrigin(origins = "*")
@RestController
public class upload {
    @Autowired
    private AliOSSUtils aliOSSUtils;
    private Url GetUrl;
    // 保存文件到本地
    @PostMapping("/avatar/upload")
    public ResultList uploadImage(MultipartFile image) throws IOException {
        // 获取原始文件名比如 index.jpg
        String originFileName = image.getOriginalFilename();
        // 构建新的文件名
//        String newFileName = UUID.randomUUID().toString()+originFileName;
        String newFileName = UUID.randomUUID().toString()+originFileName.substring(originFileName.lastIndexOf("."));
        image.transferTo(new File("D:\\Activation\\students\\src\\main\\resources\\static\\image\\"+newFileName));
        String url = "http://127.0.0.1:8080/image/"+newFileName;
        return ResultList.success(Url.ListUrl(url)); // 传递List类型的数据给ResultList.success()
    }
    // 上传至阿里云oss
    @PostMapping("/ali/upload")
    public ResultList uploadAliOSS(MultipartFile avatar) throws IOException {
        System.out.println(avatar);
        if (avatar != null){
            log.info("----------上传头像开始-----");
            String url = aliOSSUtils.upload(avatar);
            log.info("----------上传头像结束-----");
            System.out.println(url);
            return ResultList.success(Url.ListUrl(url));
        }else {
            return ResultList.error("请上传头像");
        }

    }

}
